<?php

namespace apps\api\modules\user\controllers;

use common\modules\user\logic\UserCalculationLogLogic;
use common\modules\user\logic\UserLogic;
use common\modules\user\map\UserCalculationLogMap;
use common\modules\user\map\UserSignLogMap;
use Yii;
use common\modules\user\UserSignLog;

class UserSignLogController extends \apps\api\modules\ApiBaseController
{
    public $modelClass = 'common\modules\user\UserSignLog';

    public function actionView()
    {
        try {
            $log = UserSignLog::findOne($this->userId) ?: new UserSignLog;
            return $this->returnData($log);
        } catch (\Exception $e) {
            return $this->returnExceptionError($e);
        }
    }

    public function actionCreate()
    {
        $db = UserSignLog::getDb()->beginTransaction();
        try {
            $m = UserSignLog::findOne($this->userId) ?: new UserSignLog;
            if ($m->lastSignDate == date('Y-m-d')) throw new \Exception('您今天已签到过了');
            $m->userId = $this->userId;
            // 连续签到，超过7天则还原为连续1天
            $isContinuity =  $m->lastSignDate == date('Y-m-d', strtotime('-1 day')) && $m->continuityDay < UserSignLogMap::MAX_CONTINUITY_DAY;
            $m->continuityDay = $isContinuity ? $m->continuityDay + 1 : 1;
            $m->lastSignDate = date('Y-m-d');
            $m->logicSave();
            $db->commit();
            UserLogic::addCalculationExperience($this->userId, $m->continuityDay, $m->continuityDay, UserCalculationLogMap::TYPE_SIGN);
            return $this->returnData($m);
        } catch (\Exception $e) {
            $db->rollBack();
            return $this->returnExceptionError($e);
        }
    }

}
